<?php

namespace app\home\controller;

use app\common\controller\Home;

class Post extends Home
{


    public function __construct()
    {
        parent::__construct();
        $this->PostModel = model('Post.Post');
        $this->RecordModel = model('Record');
        $this->UserModel = model('User.User');
    }
    public function add()
    {
        if ($this->request->isPost()) {
            /**
             * 消费积分 插入
             * 用户表 更新积分
             * 用户积分 -（悬赏积分 + 发帖子所需的积分）
             * 帖子表 插入
             */

            //验证码验证（先空后补）
            //验证验证码
            $vercode = $this->request->param('vercode');
            if (!captcha_check($vercode)) {
                $this->error('验证码错误');
            }

            $this->PostModel->startTrans();
            $this->RecordModel->startTrans();
            $this->UserModel->startTrans();

            //悬赏积分
            $acceptPoin = $this->request->param('point', 0);

            //帖子状态所需的积分
            $state = $this->request->param('state', 0);

            $StatePoint = model('Config')->where('key', "PostState{$state}")->value('value');

            $StatePoint = $StatePoint ? $StatePoint : 0;

            $PostPoint = bcadd($acceptPoin, $StatePoint);

            $UpdatePoint = bcsub($this->LoginUser['point'], $PostPoint);
            if ($UpdatePoint < 0) {
                $this->error('积分不足，请及时充值。');
            }
            //  halt($state);
            //封装更新用户积分
            $UserData = [
                'id' => $this->LoginUser['id'],
                'point' => $UpdatePoint
            ];
            $UserStatus = $this->UserModel->isUpdate(true)->save($UserData);

            if ($UserStatus === FALSE) {
                $this->error($this->UserModel->getError());
            }

            //接收全部参数
            $params = $this->request->param();
            // halt($params);
            //封装更新Post数据
            $PostData = [
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content'],
                'point' => $PostPoint,
                'state' => $params['state'],
                'userid' => $this->LoginUser['id']
            ];

            $PostStatus = $this->PostModel->validate('common/Post/Post')->save($PostData);

            if ($PostStatus === FALSE) {
                $this->UserModel->rollback();
                $this->error($this->PostModel->getError());
            }

            //消费记录
            $RecordData = [
                'point' => $PostPoint,
                'content' => "您发的帖子【{$PostData['title']}】成功，消费了{$PostPoint}积分",
                'state' => 1,
                'userid' => $this->LoginUser['id']
            ];
            $RecordStatus = $this->RecordModel->validate('common/User/Record')->save($RecordData);
            if ($RecordStatus === FALSE) {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->error($this->RecordModel->getError());
            }

            if ($RecordStatus === FALSE || $UserStatus === FALSE || $PostStatus === FALSE) {
                $this->UserModel->rollback();
                $this->PostModel->rollback();
                $this->RecordModel->rollback();
                $this->error('发布失败');
            } else {
                $this->UserModel->commit();
                $this->PostModel->commit();
                $this->RecordModel->commit();
                $this->success('发布成功', url('home/index/index'));
            }
        }
        //查询分类
        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();

        $StateList = $this->PostModel->state();

        return $this->fetch("", [
            "CateList" => $CateList,
            "StateList" => $StateList
        ]);
    }
    /**
     * 编辑帖子列表
     *
     * @return \think\Response
     */
    public function edit()
    {

        $postid = $this->request->param('postid', 0);
        //查询分类
        $CateList = model('Post.Cate')->order('weigh', 'desc')->limit(7)->select();
        $PostList = model('Post.Post')->where('id', $postid)->find();
        if (!$PostList) {
            $this->error('帖子不存在，请重新选择。');
        }
        // halt($postid);
        if ($PostList['userid'] != $this->LoginUser['id']) {
            $this->error('你没有权限编辑他人的帖子。');
        }
        $StateList = $this->PostModel->state();

        //
        if ($this->request->isPost()) {
            $params = $this->request->param();

            if (!captcha_check($params['vercode'])) {
                $this->error('验证码错误');
            }
            //封装更新的数据
            $data = [
                'id' => $postid,
                'cateid' => $params['cateid'],
                'title' => $params['title'],
                'content' => $params['content']
            ];

            $result = $this->PostModel->isUpdate(true)->validate('common/Post/Post.edit')->save($data);

            if ($result == FALSE) {
                $this->error('编辑失败');
            } else {
                $this->success('编辑成功', url('home/index/info', ['postid' => $postid]));
            }
        }

        return $this->fetch("", [
            "CateList" => $CateList,
            "StateList" => $StateList,
            "PostList" => $PostList
        ]);
    }

    public function del()
    {
        if ($this->request->isAjax()) {
            $postid = $this->request->param('postid', 0);

            //deletetime is null
            $post = $this->PostModel->find($postid);
            //查询sql语句
            // echo $this->PostModel->getlastsql();
            // exit;

            if (!$post) {
                $this->error("帖子不存在，无法删除");
            }

            //$result = $post->delete();
            $result = $this->PostModel->destroy($postid);
            if ($result === FALSE) {
                $this->error('删除失败');
            }

            $this->success('删除成功', url('home/index/index'));
        }
    }

    public function collect(){
        if ($this->request->isAjax()) {
            $action = $this->request->param('action',null);
            $params = $this->request->param();
            // halt($params);
            if($action == "confirm"){
                $data = [
                    'postid' => $params['postid'],
                    'userid' => $params['userid'],
                ];
                $result = model('Collect')->save($data);
                if ($result === FALSE) {
                    $this->error('收藏失败');
                }
                $this->success('收藏成功');
            }
            if($action == "cancel"){
                $postid = (int)$params['postid'];
                $userid = (int)$params['userid'];
                // halt($collectId);
                $resDel = model('Collect')->where(['postid'=>$postid,'userid'=>$userid])->delete();
                if ($resDel === FALSE) {
                    $this->error('取消收藏失败');
                }
                $this->success('已取消');
            }  
            
        }
    }
}
